import { WeaSearchGroup,WeaSelect,WeaTools ,WeaErrorPage ,WeaFormItem ,WeaBrowser,WeaDialog,WeaRightMenu,WeaHelpfulTip,WeaInput} from 'ecCom';
import {inject, observer} from "mobx-react/index";
import { Button , Modal , Icon} from 'antd';
import {WeaLocaleProvider} from 'ecCom';
import * as mobx from 'mobx';
const { toJS } = mobx;
import cloneDeep from 'lodash/cloneDeep';
import isEmpty from 'lodash/isEmpty';
const getLabel = WeaLocaleProvider.getLabel;
import { getFreeObjById , getLastObjById , isExistThisElement , getFirstParentHaveNext 
        ,checkCurrentNodeIsPassed , getElementBranchLevel} from './workflowFreeUtils';

@observer
class WorkflowFreeNode extends React.Component{
    constructor(props) {
        super(props);
        this.state = {}
    }
    render(){
        const { workflowNewDesignStore , nodeParams = {}, nodeStyle = {} , isReadOnlyModel, isFlowModel = '0',isMobile='0',belongWhereTag} = this.props;
        const { setAddDatasTypeModalShow , addDatasTypeModalShow , addDatasParams , currentMouseEneterItemId , currentChoosedItemId,wfFreeDatas,
        clearCurrentChooseState , circulationParams,getFreeObjById,nodeOperatorsReplaceDatas,globalNextNodeEditPurview,currentChoosedItemDataIndex, forecastNodeIds} = workflowNewDesignStore;
         
        const { nodeEntity = {} , noOperatedUsers = [] , operatedUsers = [] , viewedUsers = [] , parentid = '' , id=''
        , currentNodeGroup = false} = nodeParams;
        const { nodename = '' , nodetype = '1' , nodeStatus = '0' , mustPass = false , nextNodeEditPurview = '2'} = nodeEntity;

        /** 获取当前 准确位置上的自由节点数据*/
        let startId =  belongWhereTag.split('_')[0];
        let datasIndex =  belongWhereTag.split('_')[1];
        let currentFreeDatas = wfFreeDatas[startId][datasIndex];
        /************/

        const currentParentElement = getFreeObjById(parentid,currentFreeDatas) || {};
        const { mergeType = ''} = currentParentElement;
        const curOperatorsObj = nodeOperatorsReplaceDatas[id] || [];

        let curStyleObj = {} , operatorsName = '';
        if(nodeStatus == '0' || nodeStatus == '3'){// nodeStatus 0 :未处理节点  1 当前节点  2 已处理节点  3:未经过---
            curStyleObj = circulationParams.noPassedNodeShouldCheckRight;
        }else if(nodeStatus == '2'){
            curStyleObj = circulationParams.passedNodeAndNoOPeration;
        }else if(nodeStatus == '1'){
            curStyleObj = circulationParams.currentNodeAndNoOperation;
            if(currentNodeGroup){//当前节点&&(是当前人)
                curStyleObj = circulationParams.currentMustPassNode;
            }
        }

        //预测节点
        if((nodeStatus == '0' || nodeStatus == '3') && forecastNodeIds && forecastNodeIds != '' && (","+forecastNodeIds+",").indexOf(","+nodeParams.nodeid+",") > -1) {
            curStyleObj = circulationParams.forecastNode;
        }

        let needBoxShadow = !isReadOnlyModel && (currentMouseEneterItemId == nodeParams.id || nodeParams.id == currentChoosedItemId);
        const selectedStyle = {
            boxShadow : needBoxShadow ? `0 0 0 1px ${curStyleObj.borderColor}` : '' ,
            border : `1px solid ${curStyleObj.borderColor}`,
            background : `${curStyleObj.backgroundColor}`,
            cursor : isReadOnlyModel ? 'default' : 'pointer'
        }
        // 控制节点操作者的显示（先未操作 - 后已操作 且只取第一个操作者名称）
        if(noOperatedUsers.length > 0){
            let extraStr = noOperatedUsers.length > 1 ? '...' : '';
            const {userid,beAgentUserId,lastname,beAagentUserName} = noOperatedUsers[0];
            operatorsName = beAgentUserId > 0 ? `${beAagentUserName}->${lastname}`: lastname;
        }else if(operatedUsers.length > 0){
            let extraStr = operatedUsers.length > 1 ? '...' : '';
            let tempOperatedUsers = operatedUsers.filter((item) => {return item.userid == item.processUser;});
            let tempOperatedUser = tempOperatedUsers.length > 0 ?tempOperatedUsers[0] : operatedUsers[0];
            const {userid,beAgentUserId,lastname,beAagentUserName} = tempOperatedUser;
            operatorsName = beAgentUserId > 0 ? `${beAagentUserName}->${lastname}`: lastname;
        }
        if(curOperatorsObj.length > 0 && operatorsName == ''){//当节点名称上没有人员时获取
            let extraStr = curOperatorsObj.length > 1 ? '...' : '';
            operatorsName = curOperatorsObj[0].name + extraStr;
        }
        operatorsName == '' ? operatorsName = getLabel(15808,'未设置') : '';
        // 1:审批 2：提交 5：查阅
        if(isFlowModel == '1'){
            return (
                <div className={`workflow-design-free-node-v2 ${nodeParams.id}`}  
                    style = {nodeStyle} 
                    >
                    {(nodetype == '0' || nodetype == '3') ? 
                        <div className={`circleModel ${nodetype == '3' ? 'endNode' : ''}`} onMouseEnter={ !isReadOnlyModel && this.mouseEnterNode} >
                            {nodetype == '0'?
                                <div className="name" title={getLabel(506901,'流转设定节点')} >{getLabel(506901,'流转设定节点')}</div>
                                :
                                <div className="name" >...</div>
                            }
                            {!isReadOnlyModel && this.getNodeActions(nodetype,globalNextNodeEditPurview)
                            }
                        </div>
                        :
                        <div className={nodetype == '1' ? "shenpi":"chuli" }
                            onClick={this.clickNode} 
                            onMouseEnter={ !isReadOnlyModel && this.mouseEnterNode} 
                            style={selectedStyle}
                            >
                            <div className="showname" title={nodename} style={{color:curStyleObj.nodeColor}}>{nodename}</div>
                            <div className="node-operators"  title={operatorsName} style={{color:curStyleObj.operatorColor}}>{operatorsName}</div>
                            {!isReadOnlyModel && this.getNodeActions(nodetype,globalNextNodeEditPurview)
                            }
                            {this.mustPassIcon(mustPass,mergeType,nodetype)}
                        </div>
                    }
                </div>
            )
        }else{
            return (
                <div className={`workflow-design-free-node-v2 ${nodeParams.id}`}  
                    style = {nodeStyle} 
                    // draggable={true}
                    // onDragStart = {this.dragStart}
                    // onDragEnd = {this.dragDrop}
                    // onDragEnter = {this.dragEnter}
                    >
                    {
                        <div className={nodetype == '1' ? "shenpi": (nodetype == '0' || nodetype == '3') ? "circle" : "chuli" }
                            onClick={this.clickNode} 
                            onMouseEnter={ !isReadOnlyModel && this.mouseEnterNode} 
                            style={selectedStyle}
                            >
                            <div className="showname" title={nodename} style={{color:curStyleObj.nodeColor}}>{nodename}</div>
                            <div className="node-operators"  title={operatorsName} style={{color:curStyleObj.operatorColor}}>{operatorsName}</div>
                            {!isReadOnlyModel && isMobile != '1' &&  this.getNodeActions(nodetype,globalNextNodeEditPurview)
                            }
                            {this.mustPassIcon(mustPass,mergeType,nodetype)}
                            {!isReadOnlyModel && isMobile == '1' && this.getMobileEditions()}
                        </div>
                    }
                    
                </div>
            )
        }
    }
    /**必填红色箭头标识 */
    mustPassIcon = (mustPass,mergeType,nodetype) => {
        let res = [];
        // 必须通过标识 icon-coms-download icon-coms-positive-sequence
        if(mustPass && mergeType == '3'){
            res.push(
                <span 
                    className='icon-coms02-download mustPass-icon'
                    style={nodetype == '1' ? {
                        transform:'rotate(-45deg)',
                        left : '77px',
                        bottom : '-18px'
                    } : {
                        left : '44px',
                        bottom : '-44px'
                    }}
                    title={getLabel(506902,`此节点必须通过`)}
                ></span>
            );
        }
        return res;
    }
    /********* 拖拽 ************/
    dragStart = (e) => {
        const { workflowNewDesignStore , nodeParams = {}} = this.props;
        const { wfFreeDatas , wfFreeDatasPoints } = workflowNewDesignStore;

        const elementClassName = e.target.className || '';
        const id = elementClassName.split(' ')[1];
        if(id && !isNaN(id)){
            workflowNewDesignStore.dragStartItemId = id;
        }
    }
    dragEnter = (e) => {
        const { workflowNewDesignStore , nodeParams = {}} = this.props;
        const { wfFreeDatas , wfFreeDatasPoints } = workflowNewDesignStore;

        const elementClassName = e.target.className || '';
        const id = elementClassName.split(' ')[1];
        if(id && !isNaN(id)){
            workflowNewDesignStore.dragEndItemId = id;
        }
    }
    dragDrop = (e) => {
        const { workflowNewDesignStore , nodeParams = {}} = this.props;
        const { wfFreeDatas , wfFreeDatasPoints , dragEndItemId , dragStartItemId} = workflowNewDesignStore;

        let nodePoints = toJS(wfFreeDatasPoints);
        let nodeDatas = toJS(wfFreeDatas);

        if(dragEndItemId != dragStartItemId){
            let obj_1 = getFreeObjById(dragEndItemId);
            let obj_2 = getFreeObjById(dragStartItemId);
            let entity_1 = cloneDeep(obj_1.nodeEntity);
            let entity_2 = cloneDeep(obj_2.nodeEntity);

            obj_1.nodeEntity = {...entity_2};
            obj_2.nodeEntity = {...entity_1};
        }
        // console.log(e,'drag drop',nodeDatas,dragEndItemId,dragStartItemId);
    }
    /********* 拖拽 ************/
    /**移动端节点操作按钮 */
    getMobileEditions = () => {
        const { workflowNewDesignStore , nodeParams,belongWhereTag} = this.props;
        const { setPopOperatorsPanemParams , mobileChoosedElement , deleteFreeNodeItem , freeDetailSetConditions,wfFreeDatas} = workflowNewDesignStore;
        const { nodeEntity = {},id='',parentid=''} = mobileChoosedElement;
        const { nodetype = ''} = nodeEntity;
        /** 获取当前 准确位置上的自由节点数据  获取parentElement*/
        let startId =  belongWhereTag.split('_')[0];
        let datasIndex =  belongWhereTag.split('_')[1];
        let currentFreeDatas = {};
        if(startId){
            currentFreeDatas = wfFreeDatas[startId][datasIndex];
        }
        const parentElement = getFreeObjById(parentid,currentFreeDatas) || {};
        /************/
        if(nodeParams.id == id){
            let actions = [];
            actions.push(<span onClick={()=>{
                // window.parent.showHoverWindow('','/req/wfFreeFlowSet/detail');
                window.parent.historyRoute.push({
                    pathname: `/req/wfFreeFlowSet/detail`,
                    detailType:'editNode',
                    currentGroup: toJS(nodeParams),
                    parentGroup : toJS(parentElement),
                    condition:toJS(freeDetailSetConditions),
                    pcPublicFreeStore:workflowNewDesignStore
                });
            }}>{getLabel(93,'编辑')}</span>);
            actions.push(<span className="change-operators" onClick = {()=>{
                window.parent.historyRoute.push({
                    pathname: `/req/wfFreeFlowSet/detail`,
                    detailType:'operators',
                    currentGroup: toJS(nodeParams),
                    parentGroup : toJS(parentElement),
                    condition:toJS(freeDetailSetConditions),
                    pcPublicFreeStore:workflowNewDesignStore
                });
            }}>{getLabel(506885,'更改操作者')}</span>);
            actions.push(<span className="mobile-delete" onClick={()=>{deleteFreeNodeItem(id,belongWhereTag)}}>{getLabel(91,'删除')}</span>);
            let style = {};
            if(nodetype == '1'){//审批
                style = {
                    left:'-87px',
                    top:'-34px',
                    transform : 'rotate(-45deg)',
                }
            }else{//处理，审阅
                style = {
                    left:'-24px',
                    top:'-36px'
                }
            }
            return (
                <div className="mobile-operations" style={style}>{actions}</div>
            )
        }else{
            return;
        }
    }
    clickNode = (e) => {
        const { workflowNewDesignStore , nodeParams = {},isReadOnlyModel ,isMobile='0',belongWhereTag} = this.props;
        const { freeIsEditNode , getFreeNodeSetting,setPopOperatorsPanemParams,setCurrentElement_mobile,forecastNodeIds} = workflowNewDesignStore;
        if(isReadOnlyModel){
            const { pageX , pageY } = e;
            setPopOperatorsPanemParams({position:{left:pageX,top:pageY},visible:true,nodeinfo:nodeParams,forecastNodeIds});
            window.mxUtils && window.mxUtils.hideWfOperatorInfo();//关闭老流程图的操作者信息面板
            return;
        }
        e.stopPropagation();
        if(e.target.className === 'icon-coms-yonghu' || e.target.className === 'mobile-delete'){
            return;
        }
        //如果是查看 只读模式 不走请求
        if(isMobile == '0'){
            getFreeNodeSetting(nodeParams,belongWhereTag);
        }else{//点击来自移动端
            /**
            点击中间自由节点：
            1.节点正上方出现 "编辑 | 更改操作者 | 删除" 操作按钮
            2.页面下方出现添加 串行或者并行节点图标
             */
            setCurrentElement_mobile(nodeParams,false,belongWhereTag);
        }
    }
    mouseEnterNode = (e) => {
        if(e.target.className.indexOf('mustPass-icon') > -1){
            return;
        }
        const { workflowNewDesignStore , nodeParams = {}} = this.props;
        const { setCurrentMouseEnterId } = workflowNewDesignStore;
        setCurrentMouseEnterId(nodeParams.id);
    }
    getNodeActions = (nodetype='1',nextNodeEditPurview) => {//添加悬停节点时的操作按钮
        const { workflowNewDesignStore , nodeParams = {} ,isFlowModel = '0',belongWhereTag} = this.props;
        const { setFreeNodeUsers , nodeOperatorsReplaceDatas ,clearCurrentChooseState,currentMouseEneterItemId,freeDetailSetConditions = [],selectOperatorsMax} = workflowNewDesignStore;
        let actionComs = null,_replaceDatas = [];
        _replaceDatas = toJS(nodeOperatorsReplaceDatas)[nodeParams.id] || [];
        let browProps  = {
            type:17,
            title:getLabel(33210,'选择人员'),
            icon: "icon-coms-hrm",
            iconBgcolor: "#217346",
            linkUrl: "/hrm/resource/HrmResource.jsp?id=",
            isAutoComplete: 1,
            isMultCheckbox: false,
            isDetail: false,
            viewAttr: 2,
            zIndex: 1050,
            isShowGroup: true,
            isSingle:false,
            customized:true,
            memorise : true,
            replaceDatas:_replaceDatas,
            maxLength:selectOperatorsMax
        };

        if(freeDetailSetConditions.length > 0) {
            const {items = []} = toJS(freeDetailSetConditions)[0] || {};
            items.map((item)=>{
                const {domkey =[],browserConditionParam = {}} = item;
                if(domkey[0] == 'operators') {
                    const {dataParams = {},destDataParams = {},completeParams = {}} = browserConditionParam;
                    browProps['dataParams'] =  dataParams;
                    browProps['destDataParams'] =  destDataParams;
                    browProps['completeParams'] =  completeParams;
                }
            })
        }

        const {nodeChartEntity = {}} = nodeParams;
        const {del = false,edit = false,addParall = false,addNext = false} = nodeChartEntity;

        actionComs = <div className={`free-node-v2-action-area ${nodeParams.id}`} style={{background:'rgba(0,0,0,0.001)'}}
            onMouseLeave = {(e)=>{
                clearCurrentChooseState();
            }} >
            {del && currentMouseEneterItemId == nodeParams.id &&
                <div className="action-item delete" 
                    title = {getLabel(15599,'删除节点')}
                    style={nodetype=='1' ? {} : {left: '20px'}} 
                    onClick={(e)=>this.nodeActions('delete',e)}>
                    <span className="icon-coms-delete"></span>
                </div>
            }
            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@uc39us`}
                {...toJS(browProps)}
                onChange={(ids, names, datas)=> {
                    setFreeNodeUsers(nodeParams.id,ids, names, datas,belongWhereTag);
                }}
                onClick = {(e)=>e.stopPropagation()}
            >
                {edit && currentMouseEneterItemId == nodeParams.id &&
                    <div className="action-item operators" 
                        title = {getLabel(506885,'更改操作者')}
                        style={nodetype=='1' ? {} : {left:'70px'}}>
                        <span className="icon-coms-switch"></span>
                    </div>
                }
            </WeaBrowser>
            {addParall && currentMouseEneterItemId == nodeParams.id &&
                <div className="action-item addSerial" 
                    title = {getLabel(506899,'添加并行节点')}
                    style={nodetype=='1' ? {} : {}} 
                    onClick={(e)=>this.nodeActions('beParallel',e)}>
                    <span className="icon-coms-Enlarge"></span>
                </div>
            }
            {addNext && currentMouseEneterItemId == nodeParams.id &&
                <div className="action-item addParalla" 
                    title = {getLabel(506900,'添加串行节点')}
                    style={nodetype=='1' ? {} :nodetype=='0' ? 
                    {left:isFlowModel == '1' ? '55px' : '56px',bottom:isFlowModel == '1' ? '10px' : '0'} : {left:'42px'}} 
                    onClick={(e)=>this.nodeActions('beSerial',e)}>
                    <span className="icon-coms-Enlarge"></span>
                </div>
            }
        </div>
        return actionComs;
    }

    nodeActions = (type='delete',event) => {
        event.stopPropagation();
        const { workflowNewDesignStore , nodeParams = {},isFlowModel,belongWhereTag} = this.props;
        const { beSerialNodes , beParallelWithCurNode , deleteFreeNodeItem} = workflowNewDesignStore;
        if(type == 'delete'){
            deleteFreeNodeItem(nodeParams.id,belongWhereTag);
        }else if(type == 'beSerial'){
            if(nodeParams.trunkNode){
                beSerialNodes(isFlowModel=='1'?nodeParams.id:'root',belongWhereTag);
            }else{
                beSerialNodes(nodeParams.id,belongWhereTag);
            }
            
        }else if(type == 'beParallel'){
            beParallelWithCurNode(nodeParams.id,belongWhereTag)
        }
    }
}

export default WeaTools.tryCatch(React, 
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@lxokd3`} msg={ props.error ? props.error : getLabel(383324,' 对不起，该页面异常，请联系管理员 ')+'！'} />,
    {error: ""}
)(WorkflowFreeNode);